package com.demo.phone.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;


/**
 * @author Administrator
 * @since 2020-09-20
 */
@Slf4j
public class HttpUtil {

    private static Integer connectTimeout = 60000;

    private static Integer connectionRequestTimeout = 60000;

    private static Integer socketTimeout = 60000;


    private static String contentType = "application/json";

    public static final String CONTENT_TYPE = "Content-Type";


    public static JSONObject sendGet(String url, Map<String, String> header, String data) {
        HttpClient client = HttpClientBuilder.create().build();
        String getUrl = url;
        if (null != data) {
            getUrl += "?" + data;
        }
        log.info("getUrl:{}", getUrl);
        HttpGet httpGet = new HttpGet(getUrl);
        if (!CollectionUtils.isEmpty(header)) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpGet.setConfig(requestConfig);
        httpGet.addHeader(CONTENT_TYPE, contentType);
        try {
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(httpGet);
            long time = System.currentTimeMillis() - start;
            log.debug("本次请求'{}'耗时:{}ms", url, time);
            //close the connection
            String content = EntityUtils.toString(response.getEntity());
            return JSON.parseObject(content);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            HttpClientUtils.closeQuietly(client);
        }
    }

    public static String sendPost(String data, String url) throws IOException {
        return sendPost(data, null, url);
    }

    public static String sendPost(String data, Map<String, String> header, String url) throws IOException {
        StringBuffer resultBuffer = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);

        if (!CollectionUtils.isEmpty(header)) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        httpPost.addHeader(CONTENT_TYPE, contentType);
        StringEntity entity = new StringEntity(data, "UTF-8");
        httpPost.setEntity(entity);
        long start = System.currentTimeMillis();
        HttpResponse response = null;
        try {
            response = client.execute(httpPost);
            long time = System.currentTimeMillis() - start;
            log.debug("本次请求'{}'耗时:{}ms", url, time);
            resultBuffer = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            br.close();
        } catch (ClientProtocolException e) {
            log.error("ClientProtocolException:", e);
            log.warn("-----------------请求出现异常:{}-----------------", e.toString());

        } catch (IOException e) {
            log.error("IOException:", e);
            log.warn("-----------------请求出现IO异常:{}-----------------", e.toString());

        } catch (Exception e) {
            log.error("Exception:", e);
            log.warn("-----------------请求出现其他异常:{}-----------------", e.toString());

        } finally {
            //abort the request
            if (null != httpPost && !httpPost.isAborted()) {
                httpPost.abort();
            }
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        }
        return String.valueOf(resultBuffer);
    }
}
